package com.wyzt.auth.config;

import com.wyzt.auth.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@ConfigurationProperties(prefix = "wyzt.jwt")
@Data
@Slf4j
public class JwtProperties {

    private String secret;
    private String pubKeyPath;
    private String priKeyPath;
    private int expire;
    private String cookieName;
    private Integer cookieMaxAge;

    private PublicKey publicKey;
    private PrivateKey privateKey;

    //对象一旦实例化后，就应该读取公钥和私钥

    /**
     * @PostContruct：在构造方法执行之后执行该方法
     */
    @PostConstruct  //在构造函数实例化完成之后
    public void init() {
        try {
            //公钥私钥如果不存在，先生成
            File pubPath = new File(pubKeyPath);
            File priPath = new File(priKeyPath);
            if (!pubPath.exists() || !priPath.exists()) {
                //生成公钥私钥
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥私钥失败!", e);
            throw new RuntimeException();
        }

    }

}
